package cz.muni.fi.pa165.rentalofconstructionmachineryweb.rest;

import cz.muni.fi.pa165.rentalofconstructionmachinery.dto.MachineDTO;
import cz.muni.fi.pa165.rentalofconstructionmachinery.service.MachineService;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author Adam Zmrzlý
 * @version Miura (20121312)
 */
@Controller
@RequestMapping("/machine")
public class MachineController {
    
    @Autowired
    private MachineService machineService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public @ResponseBody MachineDTO add(@RequestBody MachineDTO machine, HttpServletRequest request, HttpServletResponse response) {
        machineService.addMachine(machine);
        response.setStatus(HttpStatus.CREATED.value());
        response.setHeader("Location", request.getContextPath() + "/rest/machine/" + machine.getId());
 
        return machine;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public @ResponseBody MachineDTO get(@PathVariable("id") Long id) {
        return machineService.searchForMachineById(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public @ResponseBody MachineDTO delete(@PathVariable("id") Long id, HttpServletResponse response) {
        MachineDTO machine = machineService.searchForMachineById(id);
        if (machine != null) {
            machineService.removeMachine(machine);
        } else {
            throw new IllegalArgumentException("Machine not found.");
        }
       
        response.setStatus(HttpStatus.OK.value());
       
        return null;
    }
    
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public @ResponseBody MachineDTO update(@PathVariable("id") Long id, @RequestBody MachineDTO machine, HttpServletResponse response) {
        machine.setId(id);
        machineService.modifyMachine(machine);
           
        response.setStatus(HttpStatus.OK.value());
        return machine;
    }
    
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody List<MachineDTO> getAll() {
        return machineService.listMachines();
    }
}
